<?php
namespace app\web\admin;

use app\common\builder\ZBuilder;
use app\web\model\Platform;
use app\web\model\Technician as myModel;
use app\web\model\TechnicianBalance;
use app\web\model\Experience;
use app\web\model\Reason;
use app\web\model\User;
use app\web\model\Shop;
use app\web\model\Tags;
use app\web\model\Job;
use app\web\model\TechnicianQualifications;
use app\web\model\Config;
use app\lib\model\Price;
use app\lib\model\Tool;
use Yansongda\Pay\Pay;
use think\Db;
use app\web\model\TechnicianCheck;

/**
 * 经营类目（后台）
 * @package
 */
class Technician extends Base 
{
    public $check_status = ['未审核','已审核','未通过'];
    public $gender = ['未授权','男','女'];
    public $balance_type = ['取消订单','订单结算','加项补差','提现','商家发放','用户取消订单误工费','技师路费','平台调整'];
    public function index($group = 'tab1')
    {
        $list_tab = [
            'tab1' => ['title' => '技师列表', 'url' => url('index', ['group' => 'tab1']),'count'=>myModel::where(['is_sub'=>1,'check_status'=>0])->count()],
            'tab2' => ['title' => '资质审核列表', 'url' => url('index', ['group' => 'tab2']),'count'=>TechnicianQualifications::where('status',0)->count()],
            'tab3' => ['title' => '技师相册', 'url' => url('index', ['group' => 'tab3']),'count'=>myModel::where('album_status',1)->count()],
            'tab4' => ['title' => '技师作品', 'url' => url('index', ['group' => 'tab4']),'count'=>myModel::where('works_status',1)->count()],
            'tab5' => ['title' => '技师介绍', 'url' => url('index',['group' => 'tab5']),'count'=>TechnicianCheck::where(['field_key'=>'technician_introduction','status'=>0])->count()],
            'tab6' => ['title' => '头像认证', 'url' => url('index',['group' => 'tab6']),'count'=>TechnicianCheck::where(['field_key'=>'avatarUrl','status'=>0])->count()],
            'tab7' => ['title' => '实名认证', 'url' => url('index',['group' => 'tab7']),'count'=>TechnicianCheck::where(['field_key'=>'id_card','status'=>0])->count()],
            'tab8' => ['title' => '职称审核', 'url' => url('index',['group' => 'tab8']),'count'=>TechnicianCheck::where(['field_key'=>'job_ids','status'=>0])->count()],
            'tab9' => ['title' => '承诺函审核', 'url' => url('index',['group' => 'tab9']),'count'=>TechnicianCheck::where(['field_key'=>'promise_path','status'=>0])->count()],
        ];
        $map = $this->getMap();
        if($group == 'tab1'){
            foreach ($map as $key => $value) {
                if($value[0] == 'gender') $map[$key][0] = 'a.gender';
                if($value[0] == 'check_status') $map[$key][0] = 'a.check_status';
                if($value[0] == 'experience_id') $map[$key][0] = 'a.experience_id';
                if($value[0] == 'shop_name') $map[$key][0] = 'a.shop_id';
            }
            $map[] = ['a.is_sub','=',1];

            $list = myModel::alias('a')->where($map)
                            ->leftjoin('experience b','b.id=a.experience_id')
                            ->leftjoin('shop c','c.id=a.shop_id')
                            ->field('a.id,a.avatarUrl,a.nickName,a.score,a.follow_number,a.order_number,a.balance,a.gender,a.age,a.wx_code,b.experience_name as experience_id,a.city,concat(a.province,a.city,a.area,a.address) as address,a.real_name,a.id_card,a.qualifications_status,a.shop_mobile,a.is_online,a.is_sale,a.is_sale1,a.check_status,a.is_recommend,ifnull(c.shop_name,"个人技师") as shop_name,a.longitude,a.latitude,a.latitude as location,a.period_time')
                            ->order($this->getOrder('a.sub_time desc'))
                            ->paginate();
            return ZBuilder::make('table')
                ->setTabNav($list_tab,  $group)
                ->hideCheckBox()
                ->setTableName('technician')
                ->addColumns([
                    ['shop_name','技师分类'],
                    ['nickName','昵称'],
                    ['is_recommend','红牌推荐','switch'],
                    ['is_sale1','是否上架','switch'],
                    ['is_online','是否在线','status','',['否','是']],
                    ['avatarUrl','头像','img_url'],
                    ['age','年龄'],
                    ['gender','姓别','status','',$this->gender],
                    ['wx_code','微信号'],
                    ['shop_mobile','电话'],
                    ['city','入住城市'],
                    ['address','地址'],
                    ['real_name','真实姓名'],
                    ['id_card','身份证'],
                    ['balance','余额'],
                    ['score','评分'],
                    ['follow_number','关注'],
                    ['order_number','订单数'],
                    ['experience_id','工作经验'],
                    ['period_time','合作期限'],
                    ['check_status','状态','status','',$this->check_status],
                    ['location','最后一次打卡地址'],
                    ['right_button', '操作', 'btn'],
                ])
                ->setRowList($list)
                ->setSearch(['real_name' => '真实姓名','nickName'=>'昵称','shop_mobile'=>'商户电话','city'=>'city']) // 设置搜索参数
                ->addOrder('age,balance,score,follow_number,order_number,period_time')
                ->addFilterList('check_status',$this->check_status)
                ->addFilterList('gender',$this->gender)
                ->addFilterList('shop_name',Shop::getSelectAll('is_sub=1 and check_status=1'))
                ->addFilterList('experience_id',Experience::getSelectAll())
                ->setColumnWidth('location',150)
                ->addRightButtons([
                    'edit'=>['title'=>'编辑'],
                    'check'=>['title'=>'审核','href'=>url('check',['id'=>'__id__'])],
                    'editbalance' => ['title'=>'余额调整','href'=>url('editbalance',['id'=>'__id__'])]
                ])
                // ->replaceRightButton(['check_status' => ['in','1,2']], '','check') // 修改id为1的按钮
                ->replaceRightButton(['check_status' => ['in','0,2']], '','editbalance') // 修改id为1的按钮
                // ->addTrClass('check_status0', 'check_status', '=', 0)
                ->setExtraCss($this->getCss())
                ->fetch();
        }
        if($group == 'tab2'){
            foreach ($map as $key => $value) {
                if($value[0] == 'status') $map[$key][0] = 'a.status';
            }
            $data_list = TechnicianQualifications::alias('a')
                                    ->where($map)
                                    ->leftjoin('technician b','b.id=a.technician_id')
                                    ->leftjoin('job c','c.id=a.job_id')
                                    ->field('a.id,a.qualifications_image,a.status,b.nickName,b.shop_mobile,c.job_name')
                                    ->order($this->getOrder('id desc'))
                                    ->paginate();
            return ZBuilder::make('table')
                ->setTabNav($list_tab,  $group)
                ->hideCheckBox()
                ->setTableName('technician_qualifications')
                ->addColumns([
                    ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['id'].'">'.$v.'</a>';
                        },'__data__'],
                    ['shop_mobile','技师电话'],
                    ['job_name','职称名称'],
                    ['qualifications_image','认证图片','img_url'],
                    ['status','状态','status','',['待审核','已通过','未通过']],
                    ['right_button', '操作', 'btn'],
                ])
                ->setRowList($data_list)
                ->setSearch(['nickName' => '技师昵称','job_name' => '职称名称','shop_mobile'=>'技师电话']) // 设置搜索参数
                ->addFilterList('status',['待审核','已通过','未通过'])
                ->addRightButtons(['checkqualifications'=>['title'=>'审核','href'=>url('checkqualifications',['id'=>'__id__'])]])
                // ->addTrClass('check_status0', 'status', '=', 0)
                ->setExtraCss($this->getCss())
                // ->replaceRightButton(['status' => ['in','1,2']], '','checkqualifications') // 修改id为1的按钮
                ->fetch();
        }
        if($group == 'tab3'){
            $map[] = ['a.is_sub','=',1];
            $data_list = myModel::alias('a')->where($map)
                            ->field('a.id,a.avatarUrl,a.nickName,a.gender,a.age,a.wx_code,a.real_name,a.id_card,a.shop_mobile,a.album as album1,a.album_sub_time,a.album_status')
                            ->order($this->getOrder('id desc'))
                            ->paginate()->each(function($item,$k){
                                return $this->tableImg($item,$k,'album1');
                            });
            return ZBuilder::make('table')
                ->setTabNav($list_tab, 'tab3')
                ->hideCheckBox()
                ->setTableName('technician')
                ->addColumns([
                    ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['id'].'">'.$v.'</a>';
                        },'__data__'],
                    ['shop_mobile','技师电话'],
                    ['age','年龄'],
                    ['gender','姓别','status','',$this->gender],
                    ['album1','技师相册'],
                    ['album_status','状态','status','',['未提交','待审核','已通过','未通过']],
                    ['album_sub_time','提交时间'],
                    ['right_button', '操作', 'btn'],
                ])
                ->setRowList($data_list)
                ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                ->addFilterList('album_status',['未提交','待审核','已通过','未通过'])
                ->addRightButtons(['checkalbum'=>['title'=>'审核','href'=>url('checkalbum',['id'=>'__id__'])]])
                ->replaceRightButton(['album_status' => ['in','0']], '','checkalbum') // 修改id为1的按钮
                // ->addTrClass('check_status0', 'album_status', '=', 1)
                ->setExtraCss($this->getCss())
                ->fetch();
        }

        if($group == 'tab4'){
            $map[] = ['a.is_sub','=',1];
            $data_list = myModel::alias('a')->where($map)
                            ->field('a.id,a.avatarUrl,a.nickName,a.gender,a.age,a.wx_code,a.real_name,a.id_card,a.shop_mobile,a.works as works1,a.works_sub_time,a.works_status')
                            ->order($this->getOrder('a.works_sub_time desc'))
                            ->paginate()->each(function($item,$k){
                                return $this->tableImg($item,$k,'works1');
                            });
            return ZBuilder::make('table')
                ->setTabNav($list_tab, 'tab4')
                ->hideCheckBox()
                ->setTableName('technician')
                ->addColumns([
                    ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['id'].'">'.$v.'</a>';
                        },'__data__'],
                    ['shop_mobile','技师电话'],
                    ['works1','技师作品'],
                    ['works_status','状态','status','',['未提交','待审核','已通过','未通过']],
                    ['works_sub_time','提交时间'],
                    ['right_button', '操作', 'btn'],
                ])
                ->setRowList($data_list)
                ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                ->addFilterList('works_status',['未提交','待审核','已通过','未通过'])
                ->addRightButtons(['checkworks'=>['title'=>'审核','href'=>url('checkworks',['id'=>'__id__'])]])
                ->replaceRightButton(['works_status' => ['in','0']], '','checkworks') // 修改id为1的按钮
                // ->addTrClass('check_status0', 'works_status', '=', 1)
                ->setExtraCss($this->getCss())
                ->fetch();
        }
        if($group == 'tab5'){
            $map[] = ['a.field_key','=','technician_introduction'];
            $data_list = TechnicianCheck::alias('a')
                                        ->where($map)
                                        ->leftjoin('technician b','b.id=a.technician_id')
                                        ->field('a.id,a.technician_id,a.field_key,a.field_val,a.status,a.check_time,b.nickName,b.shop_mobile,a.create_time')
                                        ->order('a.id desc')
                                        ->paginate();
            return ZBuilder::make('table')
                    ->setTabNav($list_tab,'tab5')
                    ->hideCheckbox()
                    ->setTableName('technician_check')
                    ->addColumns([
                        ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['technician_id'].'">'.$v.'</a>';
                        },'__data__'],
                        ['shop_mobile','技师电话'],
                        ['field_val','技师介绍'],
                        ['status','状态','status','',['待审核','审核成功','未通过']],
                        ['create_time','提交时间','datetime'],
                        ['right_button', '操作', 'btn'],
                    ])
                    ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                    ->addFilterList('status',['待审核','审核成功','未通过'])
                    ->addRightButtons(['checkintr'=>['title'=>'审核','href'=>url('checkintr',['id'=>'__id__'])]])
                    ->setColumnWidth('field_val',500)
                    ->setRowList($data_list)
                    ->fetch();
        }
        if($group == 'tab6'){
            $map[] = ['a.field_key','=','avatarUrl'];
            $data_list = TechnicianCheck::alias('a')
                                        ->where($map)
                                        ->leftjoin('technician b','b.id=a.technician_id')
                                        ->field('a.id,a.technician_id,a.field_key,a.field_val,a.status,a.check_time,b.nickName,b.shop_mobile,a.create_time')
                                        ->order('a.id desc')
                                        ->paginate()->each(function($item,$key){
                                            $item['avatar_similarity'] = TechnicianCheck::where(['technician_id'=>$item['technician_id'],'field_key'=>'avatar_similarity'])->limit(1)->value('field_val');
                                        });
            return ZBuilder::make('table')
                    ->setTabNav($list_tab,'tab6')
                    ->hideCheckbox()
                    ->setTableName('technician_check')
                    ->addColumns([
                        ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['technician_id'].'">'.$v.'</a>';
                        },'__data__'],
                        ['shop_mobile','技师电话'],
                        ['field_val','头像','img_url'],
                        ['avatar_similarity','相似度'],
                        ['status','状态','status','',['待审核','审核成功','未通过']],
                        ['create_time','提交时间','datetime'],
                        ['right_button', '操作', 'btn'],
                    ])
                    ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                    ->addFilterList('status',['待审核','审核成功','未通过'])
                    ->addRightButtons(['checkavarurl'=>['title'=>'审核','href'=>url('checkavarurl',['id'=>'__id__'])]])
                    ->setRowList($data_list)
                    ->fetch();
        }
        if($group == 'tab7'){
            $map[] = ['a.field_key','=','id_card'];
            $data_list = TechnicianCheck::alias('a')
                                        ->where($map)
                                        ->leftjoin('technician b','b.id=a.technician_id')
                                        ->field('a.id,a.technician_id,a.field_key,a.field_val,a.status,a.check_time,b.nickName,b.shop_mobile,a.create_time')
                                        ->order('a.id desc')
                                        ->paginate()->each(function($item,$key){
                                            $item['real_name'] = TechnicianCheck::where(['technician_id'=>$item['technician_id'],'field_key'=>'real_name'])->limit(1)->value('field_val');
                                        });
            return ZBuilder::make('table')
                    ->setTabNav($list_tab,'tab7')
                    ->hideCheckbox()
                    ->setTableName('technician_check')
                    ->addColumns([
                        ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['technician_id'].'">'.$v.'</a>';
                        },'__data__'],
                        ['shop_mobile','技师电话'],
                        ['real_name','真实姓名'],
                        ['field_val','身份证号'],
                        ['status','状态','status','',['待审核','审核成功','未通过']],
                        ['create_time','提交时间','datetime'],
                        ['right_button', '操作', 'btn'],
                    ])
                    ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                    ->addFilterList('status',['待审核','审核成功','未通过'])
                    ->addRightButtons(['checidcard'=>['title'=>'审核','href'=>url('checidcard',['id'=>'__id__'])]])
                    ->setRowList($data_list)
                    ->fetch();
        }
        if($group == 'tab8'){
            $map[] = ['a.field_key','=','job_ids'];
            $data_list = TechnicianCheck::alias('a')
                                        ->where($map)
                                        ->leftjoin('technician b','b.id=a.technician_id')
                                        ->field('a.id,a.technician_id,a.field_key,a.field_val,a.status,a.check_time,b.nickName,b.shop_mobile,a.create_time')
                                        ->order('a.id desc')
                                        ->paginate()->each(function($item,$key){
                                            $job = Job::where('id','in',$item['field_val'])->column('job_name');
                                            $item['job'] = implode(' | ', $job);
                                        });
            return ZBuilder::make('table')
                    ->setTabNav($list_tab,'tab8')
                    ->hideCheckbox()
                    ->setTableName('technician_check')
                    ->addColumns([
                        ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['technician_id'].'">'.$v.'</a>';
                        },'__data__'],
                        ['shop_mobile','技师电话'],
                        ['job','职称'],
                        ['status','状态','status','',['待审核','审核成功','未通过']],
                        ['create_time','提交时间','datetime'],
                        ['right_button', '操作', 'btn'],
                    ])
                    ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                    ->addFilterList('status',['待审核','审核成功','未通过'])
                    ->addRightButtons(['checkjob'=>['title'=>'审核','href'=>url('checkjob',['id'=>'__id__'])]])
                    ->setRowList($data_list)
                    ->fetch();
        }
        if($group == 'tab9'){
            $map[] = ['a.field_key','=','promise_path'];
            $data_list = TechnicianCheck::alias('a')
                                        ->where($map)
                                        ->leftjoin('technician b','b.id=a.technician_id')
                                        ->field('a.id,a.technician_id,a.field_key,a.field_val,a.status,a.check_time,b.nickName,b.shop_mobile,a.create_time')
                                        ->order('a.id desc')
                                        ->paginate();
            return ZBuilder::make('table')
                    ->setTabNav($list_tab,'tab9')
                    ->hideCheckbox()
                    ->setTableName('technician_check')
                    ->addColumns([
                        ['nickName','技师昵称','callback',function($v,$data){
                            return '<a target="_blank" href="'.config('api.domain').'admin.php/web/technician/edit/id/'.$data['technician_id'].'">'.$v.'</a>';
                        },'__data__'],
                        ['shop_mobile','技师电话'],
                        ['field_val','承诺函','img_url'],
                        ['status','状态','status','',['待审核','审核成功','未通过']],
                        ['create_time','提交时间','datetime'],
                        ['right_button', '操作', 'btn'],
                    ])
                    ->setSearch(['nickName' => '技师昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
                    ->addFilterList('status',['待审核','审核成功','未通过'])
                    ->addRightButtons(['checkpromise'=>['title'=>'审核','href'=>url('checkpromise',['id'=>'__id__'])]])
                    ->setRowList($data_list)
                    ->fetch();
        }
    }
    /**
     * 审核承诺函
     * [checkpromise description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkpromise($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = TechnicianCheck::get($id);
        if($this->request->isPost()){
            $data = $this->request->post();
            if($data['status'] == 2){
                if(empty($data['reason_id'])) $this->error('请选择不予通过原因');
                $data['no_check_desc'] = $reason[$data['reason_id']];
            }elseif($data['status'] == 1){
                $technician = myModel::get($info->technician_id);
                $technician->promise_path = $info->field_val;
                $technician->save();
            }
            $data['check_time'] = time();
            $info->save($data);
            $this->success('操作成功','index?group=tab9');
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['gallery','field_val','承诺函'],
                ['radio', 'status', '审核状态', '', ['待审核','通过','不予通过'], 0],
                ['select','reason_id','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','reason_id',false)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 审核职称
     * [checkjob description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkjob($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = TechnicianCheck::get($id);
        if($this->request->isPost()){
            $data = $this->request->post();
            $data['field_val'] = implode(',',$data['field_val']);
            if($data['status'] == 2){
                if(empty($data['reason_id'])) $this->error('请选择不予通过原因');
                $data['no_check_desc'] = $reason[$data['reason_id']];
            }elseif($data['status'] == 1){
                if(empty($data['field_val'])) $this->error('请至少选择一个职称');
                $technician = myModel::get($info->technician_id);
                $technician->job_ids = $data['field_val'];
                $technician->save();
            }
            $data['check_time'] = time();
            $info->save($data);
            $this->success('操作成功','index?group=tab8');
        }
        $job = Job::getSelectAll();
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['checkbox','field_val','职称','',$job],
                ['radio', 'status', '审核状态', '', ['待审核','通过','不予通过'], 0],
                ['select','reason_id','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','reason_id',false)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 实名认证
     * [checidcard description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checidcard($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = TechnicianCheck::get($id);
        $real_name = TechnicianCheck::where(['technician_id'=>$info->technician_id,'field_key'=>'real_name'])->find();
        if($this->request->isPost()){
            $data = $this->request->post();
            if($data['status'] == 2){
                if(empty($data['reason_id'])) $this->error('请选择不予通过原因');
                $data['no_check_desc'] = $reason[$data['reason_id']];
            }elseif($data['status'] == 1){
                $technician = myModel::get($info->technician_id);
                $technician->real_name = $real_name->field_val;
                $technician->id_card = $info['field_val'];
                $technician->age = Tool::getAgeByID($info['field_val']);
                $technician->gender = Tool::getSex($info['field_val']);
                $technician->save();
            }
            $data['check_time'] = time();
            $info->save($data);
            unset($data['id']);
            $real_name->save($data);
            $this->success('操作成功','index?group=tab7');
        }
        $info->real_name = $real_name['field_val'];
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['static','real_name','真实姓名'],
                ['static','field_val','身份证号'],
                ['radio', 'status', '审核状态', '', ['待审核','通过','不予通过'], 0],
                ['select','reason_id','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','reason_id',false)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 审核头像
     * [checkavarurl description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkavarurl($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = TechnicianCheck::get($id);
        $avatar_similarity = TechnicianCheck::where(['technician_id'=>$info->technician_id,'field_key'=>'avatar_similarity'])->find();
        if($this->request->isPost()){
            $data = $this->request->post();
            if($data['status'] == 2){
                if(empty($data['reason_id'])) $this->error('请选择不予通过原因');
                $data['no_check_desc'] = $reason[$data['reason_id']];
            }elseif($data['status'] == 1){
                $technician = myModel::get($info->technician_id);
                $technician->avatarUrl = $info->field_val;
                $technician->avatar_similarity = $avatar_similarity['field_val'];
                $technician->save();
            }
            $data['check_time'] = time();
            $info->save($data);
            unset($data['id']);
            $avatar_similarity->save($data);
            $this->success('操作成功','index?group=tab6');
        }
        $info->avatar_similarity = $avatar_similarity['field_val'];
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['gallery','field_val','头像'],
                ['static','avatar_similarity','相似度'],
                ['radio', 'status', '审核状态', '', ['待审核','通过','不予通过'], 0],
                ['select','reason_id','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','reason_id',false)
            ->setFormData($info)
            ->fetch();
    }
    //审核技师简介
    public function checkintr($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = TechnicianCheck::get($id);
        if($this->request->isPost()){
            $data = $this->request->post();
            if($data['status'] == 2){
                if(empty($data['reason_id'])) $this->error('请选择不予通过原因');
                $data['no_check_desc'] = $reason[$data['reason_id']];
            }elseif($data['status'] == 1){
                $technician = myModel::get($info->technician_id);
                $technician->technician_introduction = $info->field_val;
                $technician->save();
            }
            $data['check_time'] = time();
            $info->save($data);
            $this->success('操作成功','index?group=tab5');
            
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['textarea','field_val','技师介绍'],
                ['radio', 'status', '审核状态', '', ['待审核','通过','不予通过'], 0],
                ['select','reason_id','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','reason_id',false)
            ->setFormData($info)
            ->fetch();
    }
    public function checkworks($id = 0)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['works_status'] += 2;
            if($data['works_status'] == 3){
                if(!$data['works_reason']) $this->error('请选择不予通过原因');
                $data['works_reason'] = $reason[$data['works_reason']];
            }
            $data['works_check_time'] = time();
            $res = myModel::where('id',$data['id'])->update($data);
            if($res){
                $this->success('操作成功','index?group=tab4');
            }
            $this->error('操作失败');
        }
        $info = myModel::where('id',$id)
                            ->field('id,works as works1')
                            ->find();
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['gallery','works1','技师作品'],
                ['radio', 'works_status', '审核状态', '', ['通过','不予通过'], 0],
                ['select','works_reason','不予通过原因','',$reason]
            ])
            ->setTrigger('works_status','1','works_reason')
            ->setFormData($info)
            ->fetch();
    }
    public function checkalbum($id = 0)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['album_status'] += 2;
            if($data['album_status'] == 3){
                if(!$data['album_reason']) $this->error('请选择不予通过原因');
                $data['album_reason'] = $reason[$data['album_reason']];
            }
            $data['album_check_time'] = time();
            $res = myModel::where('id',$data['id'])->update($data);
            if($res){
                $this->success('操作成功','index?group=tab3');
            }
            $this->error('操作失败');
        }
        $info = myModel::where('id',$id)
                            ->field('id,album as album1')
                            ->find();
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['gallery','album1','技师相册'],
                ['radio', 'album_status', '审核状态', '', ['通过','不予通过'], 0],
                ['select','album_reason','不予通过原因','',$reason]
            ])
            ->setTrigger('album_status','1','album_reason')
            ->setFormData($info)
            ->fetch();
    }
    public function editbalance($id)
    {
        $info = myModel::get($id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(!$data['notes']) $this->error('调整余额备注不能为空');
            $change_balance = Price::pricecalc($data['balance1'],'-',$info['balance']);
            Db::startTrans();
            $res = TechnicianBalance::change($data['id'],$change_balance,7,$data['notes']);
            if($res){
                Db::commit();
                $this->success('操作成功','index?group=tab1');
            }
            Db::rollback();
            $this->error('操作失败');
        }
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['static','balance','技师余额'],
                ['number','balance1','调整后余额'],
                ['text','notes','备注']
            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 快速编辑
     * @param array $record 行为日志内容
     * @author 蔡伟明 <314013107@qq.com>
     */
    // public function quickEdit($record = [])
    // {
    //     $field           = input('post.name', '');
    //     $value           = input('post.value', '');
    //     $type            = input('post.type', '');
    //     $id              = input('post.pk', '');
    //     $validate        = input('post.validate', '');
    //     $validate_fields = input('post.validate_fields', '');

    //     $field == '' && $this->error('缺少字段名');
    //     $id    == '' && $this->error('缺少主键值');

    //     $Model = $this->getCurrModel();
    //     $protect_table = [
    //         '__ADMIN_USER__',
    //         '__ADMIN_ROLE__',
    //         config('database.prefix').'admin_user',
    //         config('database.prefix').'admin_role',
    //     ];

    //     // 验证是否操作管理员
    //     if (in_array($Model->getTable(), $protect_table) && $id == 1) {
    //         $this->error('禁止操作超级管理员');
    //     }

    //     // 验证器
    //     if ($validate != '') {
    //         $validate_fields = array_flip(explode(',', $validate_fields));
    //         if (isset($validate_fields[$field])) {
    //             $result = $this->validate([$field => $value], $validate.'.'.$field);
    //             if (true !== $result) $this->error($result);
    //         }
    //     }

    //     switch ($type) {
    //         // 日期时间需要转为时间戳
    //         case 'combodate':
    //             $value = strtotime($value);
    //             break;
    //         // 开关
    //         case 'switch':
    //             $value = $value == 'true' ? 1 : 0;
    //             break;
    //         // 开关
    //         case 'password':
    //             $value = Hash::make((string)$value);
    //             break;
    //     }

    //     // 主键名
    //     $pk     = $Model->getPk();
    //     if($field == 'is_recommend'){
    //         $shop_id = myModel::where(['id'=>$id])->value('shop_id');
    //         if($shop_id > 0) $this->error('已绑定商家不可操作');
    //     }
    //     $result = $Model->where($pk, $id)->setField($field, $value);

    //     cache('hook_plugins', null);
    //     cache('system_config', null);
    //     cache('access_menus', null);
    //     if (false !== $result) {
    //         // 记录行为日志
    //         if (!empty($record)) {
    //             call_user_func_array('action_log', $record);
    //         }
    //         $this->success('操作成功');
    //     } else {
    //         $this->error('操作失败');
    //     }
    // }
    /**
     * 审核资质认证
     * [checkqualifications description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkqualifications($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['status'] == 2){
                if(!$data['check_reason']) $this->error('请选择不予通过原因');
                $data['check_reason'] = $reason[$data['check_reason']];
            }
            $data['check_time'] = time();
            $data['check_uid'] = UID;
            $data['update_time'] = time();
            $res = TechnicianQualifications::where('id',$data['id'])->update($data);
            if($res){
                if(TechnicianQualifications::where(['technician_id'=>$data['technician_id']])->count() == TechnicianQualifications::where(['technician_id'=>$data['technician_id'],'status'=>1])->count()){
                    myModel::where('id',$data['technician_id'])->update(['qualifications_status'=>1]);
                }
                $this->success('操作成功','index?group=tab2');
            }
            $this->error('操作失败');
        }
        $info = TechnicianQualifications::alias('a')
                                    ->where('a.id',$id)
                                    ->leftjoin('technician b','b.id=a.technician_id')
                                    ->leftjoin('job c','c.id=a.job_id')
                                    ->field('a.id,a.qualifications_image,a.status,b.nickName,b.shop_mobile,c.job_name,a.technician_id')
                                    ->find();
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['hidden','technician_id'],
                ['static','job_name','职称名称'],
                ['gallery','qualifications_image','资质认证'],
                ['radio', 'status', '审核状态', '', ['未审核','通过','不予通过'], 0],
                ['select','check_reason','不予通过原因','',$reason]
            ])
            ->setTrigger('status','2','check_reason')
            ->setFormData($info)
            ->fetch();
    }
    public function check($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = myModel::where('id',$id)->field('id,user_id,tags_ids,order_rate,plus_rate,project_recommend,shop_id')->find();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['check_status'] += 1;
          
            if($data['check_status'] == 2){
                if(!$data['check_reason']) $this->error('请选择不予通过原因');
                $data['check_reason'] = $reason[$data['check_reason']];
                $data['order_rate'] = 0;
                $data['plus_rate'] = 0;
            }else{
                if(empty($data['order_rate']))  $this->error('请输入订单抽佣比例');
                if(empty($data['plus_rate']))  $this->error('请输入加项/补差抽佣比例');
            }
            $data['check_time'] = $this->request->time();
            $data['check_uid'] = UID;
            $data['tags_ids'] = isset($data['tags_ids']) ? implode(',',$data['tags_ids']) : '';
            $data['update_time'] = $this->request->time();
            if (myModel::where('id',$data['id'])->update($data)) {
                if($data['check_status'] == 1){  //审核通过
                    $user = User::get($info['user_id']);
                    $user->technician_id = $info['id'];
                    $user->save();
                }elseif($data['check_status'] == 2){ //审核不通过 修改用户表中的technician_id
                    User::where('id',$info['user_id'])->update(['technician_id'=>0]);
                }
                $this->success('操作成功','index');
            } else {
                $this->error('操作失败');
            }
        }
    
        $tags = Tags::getSelectAll();
        $addFormItems = [
            ['hidden','id'],
            ['radio', 'check_status', '技师审核状态', '', ['通过','不予通过'], 0],
            ['checkbox','tags_ids','技师标签','',$tags],
            ['number','order_rate','订单抽佣比例','0.1表示10%'],
            ['number','plus_rate','加项/补差抽佣比例','0.1表示10%'],
            ['number','project_recommend','项目推荐数量'],
            ['select','check_reason','不予通过原因','',$reason]
        ];
        if($info->shop_id > 0){
            unset($addFormItems[5]);
        }
        return ZBuilder::make('form')
            ->addFormItems($addFormItems)
            ->setTrigger('check_status','1','check_reason')
            ->setTrigger('check_status','0','tags_ids,order_rate,plus_rate')
            ->setFormData($info)
            ->fetch();
    }
    public function edit($id = null)
    {
        $info = myModel::alias('a')
                        ->leftjoin('experience b','b.id=a.experience_id')
                        ->field('a.*,concat(a.province,a.city,a.area,a.address) as address,b.experience_name')
                        ->where('a.id',$id)
                        ->find()->getData();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $info = myModel::get($data['id']);
            $data['period_time'] = $data['period'] == 0 ? 0 : ($info->check_time ? strtotime($info->check_time) : 0)  + 86400*$data['period'];
            $data['is_period'] = $data['period_time'] > 0 && $data['period_time'] < time() ? 1 : 0;
            $info->save($data);
            $this->success('提交成功','index');
        }

        $info['works'] = $info['works_status'] == 2 ? $info['works'] : '';
        $info['album'] = $info['album_status'] == 2 ? $info['album'] : '';
     
        $info['check_status'] = $this->check_status[$info['check_status']];
        $info['gender'] = $this->gender[$info['gender']];
    
        $job = Job::getSelectAll();
        $addFormItems = [
                ['hidden','id'],
                ['gallery','avatarUrl','头像'],
                ['static:6','real_name','真实姓名'],
                ['static:6','check_status','审核状态'],
                ['checkbox','job_ids','职称','',$job],
                ['static:6','id_card','身份证号'],
                ['static:6','nickName','昵称'],
                ['static:6','age','年龄'],
                ['static:6','gender','性别'],
                ['static:6','wx_code','微信号'],
                ['static:6','shop_mobile','商户电话'],
                ['static:6','address','地址'],
                ['static:6','balance','余额'],
                ['static:6','score','评分'],
                ['static:6','follow_number','关注度'],
                ['static:6','order_number','订单数'],
                ['static:6','experience_name','工作经验'],
                ['number:6','order_rate','订单抽佣比例','0.1表示10%'],
                ['number:6','plus_rate','加项/补差抽佣比例','0.1表示10%'],
                ['number:6','project_recommend','项目推荐数量'],
                ['number:6','period','合作期限('.($info['period_time'] == 0 ? '无期限' : date('Y-m-d H:i',$info['period_time'])).')','自审核通过后N天到期0表示无限期'],
                ['static','technician_introduction','个人简介'],
                ['gallery','promise_path','承诺函'],
                ['gallery','album','技师相册'],
                ['gallery','works','技师作品'],
            ];
        if($info['shop_id'] > 0){
            unset($addFormItems[18]);
        }
        return ZBuilder::make('form')
            ->addFormItems($addFormItems)
            ->setFormData($info)
            ->fetch();
    }


    public function withdrawal()
    {
        $map = $this->getMap();
        $map[] = ['a.balance_type','=',3];
        $list = TechnicianBalance::alias('a')
                        ->leftjoin('technician b','b.id=a.t_id')
                        ->field('a.id,abs(a.change_balance) as change_balance,a.status,b.nickName,b.shop_mobile,a.create_time')
                        ->where($map)
                        ->order($this->getOrder('a.id desc'))
                        ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('technician_balance')
            ->setSearch(['nickName' => '昵称','shop_mobile'=>'技师电话']) // 设置搜索参数
            ->addColumns([
                ['nickName','昵称'],
                ['shop_mobile','技师电话'],
                ['change_balance','提现金额'],
                ['status','审核状态','status','',['未审核','已通过','未通过']],
                ['create_time','提交时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addOrder('change_balance,create_time')
            ->addFilterList('status',['未审核','已通过','未通过'])
            ->addRightButtons(['checkwithdrawal'=>['title'=>'审核','href'=>url('checkwithdrawal',['id'=>'__id__'])]])
            ->replaceRightButton(['status' => ['in','1,2']], '','checkwithdrawal') // 修改id为1的按钮
            ->setRowList($list)
            ->fetch();
    }
    /**
     * 技师提现
     * [checkwithdrawal description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function checkwithdrawal($id)
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            $info = TechnicianBalance::get($data['id']);
            if($data['status'] == 0) $this->success('操作成功' ,'withdrawal');
            if($data['status'] == 2){
                $res = $info->save($data);
                if(!$res) $this->error('操作失败');
                $this->success('操作成功','withdrawal');
            }
            if($data['status'] == 1){

                $user = myModel::get($info['t_id']);

                if(bccomp($user->balance, abs($info['change_balance']),2) == -1){
                    $this->error('可提现余额不足');
                }
                $order = [
                    'partner_trade_no' => $this->getOrderNo(),              //商户订单号
                    'openid' => $user['openid'],                        //收款人的openid
                    'check_name' => 'NO_CHECK',            //NO_CHECK：不校验真实姓名\FORCE_CHECK：强校验真实姓名
                    // 're_user_name'=>'张三',              //check_name为 FORCE_CHECK 校验实名的时候必须提交
                    'amount' => Price::priceyuantofen(-$info['change_balance']),                       //企业付款金额，单位为分
                    'desc' => '帐户提现',                  //付款说明
                    'type' => 'miniapp'
                ];
                try{
                    $res = Pay::wechat(Config::getWechatConfig(1))->transfer($order);
                } catch (\Exception $e) {
                    $this->error("支付接口异常".$e->getMessage());
                } 
          
                if($res['return_code'] == 'SUCCESS'){
                    $data['before_balance'] = $user['balance'];
                    $af_balanc = Price::pricecalc($user['balance'],'+',$info['change_balance']);
                    $data['after_balance'] = $af_balanc;
                    $user->balance = $af_balanc;
                    $user->save();
                    $info->save($data);
                    Platform::change([
                        'role' => 1,
                        'p_id' => $user['id'],
                        'platform_type' => 5,
                        'mobile' => $user['shop_mobile'],
                        'user_name' => $user['nickName'],
                        'change_balance' => $info['change_balance'],
                        'notes' => '技师提现到零钱'
                    ]);
                    $this->success('提现成功','withdrawal');
                }
                $this->error('提现失败');
            }
        }
        $info = TechnicianBalance::field('id,abs(change_balance) as change_balance,status,t_id')->get($id);
        $info->tot_withdrawal = TechnicianBalance::where(['t_id'=>$info->t_id,'balance_type'=>3,'status'=>1])->sum('change_balance');
        $info->tot_withdrawal = abs($info->tot_withdrawal);
        $info->withdrawal_balance = MyModel::where('id',$info->t_id)->value('balance');

        $list = TechnicianBalance::where(['t_id'=>$info->t_id,'balance_type'=>3,'status'=>1])
                            ->field('id,t_id,abs(change_balance) as change_balance,create_time')
                            ->select()
                            ->toArray();
        $info['order_goods'] = $list;
        $content = "";
        foreach ($list as $key => $v) {
            $content .= "<tr>
                            <td>{$v['change_balance']}</td>
                            <td>{$v['create_time']}</td>
                        </tr>";
        }
        $html = <<<EOF
<div  id="product-table" style="display:none">
    <table class="table table-builder table-hover table-bordered table-striped ">
        <tr>
            <th>提现金额</th>
            <th>提现时间</th>
        </tr>
        {$content}
    </table>
</div>
<script>
    $(function(){
        $("#form_group_goods .form-control-static").html($("#product-table").html());

    })
</script>
EOF;
        return ZBuilder::make('form')
            ->setPageTips('审核通过后提现金额直接到账微信')
            ->addFormItems([
                ['hidden','id'],
                ['static','withdrawal_balance','该用户可提现余额(元)'],
                ['static','tot_withdrawal','该用户总共提现金额(元)'],
                ['static', 'change_balance','提现金额'],
                ['radio', 'status', '状态', '', ['未审核','已通过','未通过'], 1],
            ])
            ->addStatic('goods', '提现记录')
            ->setExtraHtml($html)
            ->setFormData($info)
            ->fetch();
    }
    public function balance()
    {
        $map = $this->getMap();
        $map[] = ['a.status','=',1];
        foreach ($map as $key => $value) {
            if($value[0] == 'update_time') $map[$key][0] = 'a.update_time';
        }
        $list = TechnicianBalance::alias('a')
                        ->leftjoin('technician b','b.id=a.t_id')
                        ->field('a.id,b.wx_code,a.balance_type,b.city,a.before_balance,a.after_balance,a.change_balance,a.notes,a.status,b.nickName,b.shop_mobile,a.update_time')
                        ->where($map)
                        ->order($this->getOrder('a.update_time desc'))
                        ->paginate();
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('technician_balance')
            ->setSearch(['nickName' => '昵称','shop_mobile'=>'技师电话','city'=>'城市']) // 设置搜索参数
            ->addColumns([
                ['nickName','昵称'],
                ['wx_code','微信号'],
                ['shop_mobile','技师电话'],
                ['city','所在城市'],
                ['balance_type','变动类型','status','',$this->balance_type],
                ['before_balance','变动前金额'],
                ['change_balance','变动金额'],
                ['after_balance','变动后金额'],
                ['notes','备注'],
                ['update_time','变动时间'],
            ])
            ->addTimeFilter('update_time','','变动时间')
            ->addFilterList('balance_type',$this->balance_type)
            ->addOrder('change_balance,update_time')
            ->setRowList($list)
            ->fetch();
    }

}